<template>
	<view class="container">
		<view class="search-bar">
			<uni-search-bar v-model.trim="msg" placeholder="想租什么,搜一搜" cancelButton="none" clearButton="none"
				radius="100" :width="500" />
			<view class="search-btn" :class="{active:msg}" @click="handleSearch">搜索</view>
		</view>
		<!-- 搜索历史 -->
		<view class="history" v-if="historyList.length !== 0">
			<search-history :historyList="historyList" @cleanHistory="cleanHistory" @toGoodsList="toGoodsList">
			</search-history>
		</view>
		<!-- 热门推荐 -->
		<view class="hot-search">
			<view class="">热门搜索</view>
			<hot-list :hotList="hotList" @toGoodsList="toGoodsList"></hot-list>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				msg: '',
				hotList: [], //热门搜索列表
				historyList: [] //搜索历史列表
			}
		},
		onLoad() {
			this.getHot();
			this.historyList = JSON.parse(uni.getStorageSync('history') || '[]')
		},
		methods: {
			getHot() {
				uni.$http.get("/Wechat/Index/keywords")
					.then(res => {
						if (res.data.status === 200) {
							const data = res.data.data;
							this.hotList.push(...data)
						}
					})
			},
			toGoodsList(val) {
				this.msg = val;
				this.handleSearch();
			},
			cleanHistory() {
				this.historyList = [];
				uni.setStorageSync('history', JSON.stringify(this.historyList));
			},
			handleSearch() {
				const index = this.historyList.findIndex(item => item == this.msg);
				if (index == -1) {
					this.historyList.unshift(this.msg);
				} else {
					this.historyList.splice(index, 1);
					this.historyList.unshift(this.msg);
				}
				uni.setStorageSync('history', JSON.stringify(this.historyList));
				uni.navigateTo({
					url: `/pagesA/category/goods/goodsList/goodsList?val=${ this.msg }`,
				})
				this.msg = '';
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 1vh 3vw;
	}

	.search-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.hot-search {
		margin-top: 20rpx;
	}


	.search-btn {
		width: 100rpx;
		height: 62rpx;
		text-align: center;
		line-height: 62rpx;
		border-radius: 25rpx;
		color: white;
		background-color: #d3d3d3;

		&.active {
			background-color: #f62221;
		}
	}
</style>
